<template>
  <el-row class="p-5 pt-0" @keyup.enter="getData">

    <el-col v-if="showSearch">
      <el-form ref="searchForm" :inline="true" :model="search" class="demo-form-inline">
        <el-form-item label="字典名称" class="font-black">
          <el-input v-model="search.dictName" :disabled="loading" :size="store.layoutSize" clearable
                    style="width: 180px"
                    placeholder="请输入字典名称"/>
        </el-form-item>
        <el-form-item label="字典类型" class="font-black">
          <el-input v-model="search.dictType" :disabled="loading" :size="store.layoutSize" clearable
                    style="width: 180px"
                    placeholder="请输入字典类型"/>
        </el-form-item>
        <el-form-item label="状态" class="font-black">
          <el-select v-model="search.status" :disabled="loading" :size="store.layoutSize" clearable style="width: 100px"
                     placeholder="状态" @change="getData">
            <el-option v-for="item in statusData.data" :label="item.dictLabel" :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" class="font-black">
          <el-date-picker v-model="date"
                          :disabled="loading"
                          :shortcuts="shortcuts"
                          :size="store.layoutSize"
                          clearable
                          end-placeholder="结束日期"
                          range-separator="-"
                          start-placeholder="开始日期"
                          style="width: 210px"
                          type="daterange"
                          unlink-panels
                          value-format="YYYY-MM-DD"
                          @change="getData"
          />
        </el-form-item>
        <el-form-item>
          <el-button :color="store.getTheme" :disabled="loading" :icon="Search" :size="store.layoutSize"
                     auto-insert-space type="primary" @click="getData">
            查询
          </el-button>
          <el-button :color="store.getTheme" :disabled="loading" :icon="Refresh" :size="store.layoutSize"
                     auto-insert-space
                     plain @click="resetForm">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-col class="flex justify-between">
      <div>
        <el-button :color="store.getTheme" :disabled="loading" :icon="Plus" :size="store.layoutSize" auto-insert-space
                   plain type="primary"
                   @click="add">新增
        </el-button>
        <el-button :disabled="loading || tableDictData.data.length === 0" :icon="Download" :size="store.layoutSize"
                   auto-insert-space
                   plain type="warning">
          导出
        </el-button>
      </div>
      <div>
        <el-tooltip
            class="box-item"
            effect="dark"
            :content="showSearch?'隐藏搜索':'显示搜索'"
            placement="top"
        >
          <el-button :color="store.getTheme" :size="store.layoutSize" :icon="Search" @click="showSearch = !showSearch"
                     circle/>
        </el-tooltip>
        <el-tooltip
            class="box-item"
            effect="dark"
            content="刷新"
            placement="top"
        >
          <el-button :color="store.getTheme" :disabled="loading" :icon="Refresh" :size="store.layoutSize"
                     @click="getData"
                     circle/>
        </el-tooltip>
      </div>
    </el-col>

    <el-col class="mt-2">
      <el-table :size="store.layoutSize" v-loading="loading" element-loading-text="正在努力加载中..."
                :data="tableDictData.data"
                empty-text="无数据" highlight-current-row row-key="dictId"
                style="width: 100%" table-layout="auto" @row-dblclick="rowClick">

        <el-table-column align="center" label="字典名称" prop="dictName"/>

        <el-table-column align="center" label="字典类型">
          <template #default="scope">
            <el-link :underline="false" @click="toDictData(scope.row.dictType)" :style="{color: store.getTheme}"
                     type="primary" class="text-xs">
              {{ scope.row.dictType }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column align="center" label="状态" width="150">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">{{
                scope.row.status === '0' ? '正常' : '停用'
              }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="备注" width="180" prop="remark"/>

        <el-table-column align="center" label="创建时间" width="180">
          <template #default="scope">
            {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="180">
          <template #default="scope">
            <el-link :size="store.layoutSize" :underline="false" class="text-xs" :style="{color: store.getTheme}"
                     @click="update(scope.row)">
              <el-icon>
                <EditPen/>
              </el-icon>
              修改
            </el-link>
            <el-link :size="store.layoutSize" :underline="false" class="text-xs ml-3" :style="{color: store.getTheme}"
                     @click="del(scope.row)">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <el-col class="mt-3 flex justify-end">
      <el-pagination
          :small="store.layoutSize === 'small'"
          :default-current-page="search.pageNum"
          :currentPage="search.pageNum"
          :page-size='search.pageSize'
          :page-sizes="[10, 20, 50, 100]"
          :pager-count="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="search.total"
          @size-change="handlePageSiezeChange"
          @current-change="handleCurrentPageChange"
      />
    </el-col>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称"/>
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="radio">
            <el-radio v-for="item in statusData.data" :key="item.dictCode" :label="item.dictValue">{{
                item.dictLabel
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex justify-end">
        <el-button :color="store.getTheme" :loading="btnLoading" auto-insert-space type="primary"
                   @click="submitForm(ruleFormRef)">确定
        </el-button>
        <el-button auto-insert-space @click="open = false">取消</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {useStore} from "@/store";
import {Delete, Download, EditPen, Plus, Refresh, Search} from "@element-plus/icons-vue"
import {delDictTypeData, getDictTypeData, saveDictTypeData} from "@/api/dictType";
import moment from 'moment'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessageBox, ElNotification} from "element-plus";
import {getDictData} from "@/api/dictData";
import {useRouter} from "vue-router";

//创建store
const store = useStore()

const router = useRouter()

//跳转字典数据管理
function toDictData(dictType) {
  router.push({
    path: `/dict-data/${dictType}`
  })
}

//单元格双击事件
function rowClick(val) {
  router.push({
    path: `/dict-data/${val.dictType}`
  })
}

//单选按钮
const radio = ref('0')

//弹出层标题
const title = ref("")

//是否显示弹出层
const open = ref(false)

//显示搜索框
const showSearch = ref(true)

//默认禁用删除按钮
const delDisabled = ref(true)

//表格加载
const loading = ref(false)

//绑定创建时间区间
const date = ref([])

//赋值状态信息
const statusData = reactive({
  data: []
})
getDictData({'dictType': 'sys_normal_disable'}).then(result => {
  statusData.data = result.data.data
})

const searchForm = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()

//新增、修改表单数据
const form = reactive({
  dictId: null,
  dictName: null,
  dictType: null,
  status: null,
  remark: null,
  createBy: null,
  updateBy: null
})

//清除
function clearForm() {
  form.dictId = null
  form.status = null
  form.dictType = null
  form.dictName = null
  form.remark = null
  form.createBy = null
  form.updateBy = null
}

//新增字典类型事件
function add() {
  clearForm()
  radio.value = '0'
  title.value = '新增字典类型'
  open.value = true
}

//修改字典类型事件
function update(params: any) {
  clearForm()
  radio.value = params.status
  form.dictType = params.dictType
  form.dictName = params.dictName
  form.remark = params.remark
  form.dictId = params.dictId
  title.value = '修改字典类型'
  open.value = true
}

//删除方法
function del(val) {
  ElMessageBox.confirm('您确定要删除<' + val.dictName + '>字典吗？', '警告', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delDictTypeData({dictId: val.dictId}).then(result => {
      if (result.data.code === 200) {
        ElNotification({
          message: result.data.msg,
          type: 'success'
        })
      }
      getData()
    })
  })
}

//表单校验
const rules = reactive<FormRules>({
  dictName: [
    {required: true, message: "字典名称不能为空", trigger: "blur"}
  ],
  dictType: [
    {required: true, message: "字典类型不能为空", trigger: "blur"}
  ]
})

const btnLoading = ref(false)

//提交新增、修改表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      btnLoading.value = true
      form.status = radio.value
      if (form.dictId && form.dictId != '') {
        form.updateBy = store.getUser.userName
      } else {
        form.createBy = store.getUser.userName
      }
      saveDictTypeData(form).then(result => {
        if (result.data.code === 200) {
          ElNotification({
            message: result.data.msg,
            type: 'success'
          })
          open.value = false
        }
        getData()
        btnLoading.value = false
      })
    }
  })
}

//重置表单
function resetForm() {
  date.value = []
  search.dictName = null
  search.dictType = null
  search.status = null
  search.startDate = null
  search.endDate = null
  getData()
}

//查询表单数据
const search = reactive({
  dictName: null,
  dictType: null,
  status: null,
  pageNum: 1,
  pageSize: 10,
  total: 0,
  startDate: null,
  endDate: null,
})

//分页控制
function handleCurrentPageChange(val) {
  search.pageNum = val
  //获取数据
  getData()
}

//页大小控制
function handlePageSiezeChange(val) {
  search.pageSize = val
  //获取数据
  getData()
}

//赋值获取到的数据
const tableDictData = reactive({
  data: []
})
getData()

function getData() {
  loading.value = true;
  if (date.value && date.value.length > 0) {
    search.startDate = date.value[0]
    search.endDate = date.value[1]
  } else {
    search.startDate = null
    search.endDate = null
  }
  getDictTypeData(search).then(result => {
    search.total = result.data.data.total
    tableDictData.data = result.data.data.list
    loading.value = false
  })
}

//时间选择器快捷选择
const shortcuts = [
  {
    text: '上周内',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

</script>

<style scoped>

</style>
